//获取应用实例
var app = getApp();
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var utils = require('../../utils/utils');
var storage = require('../../utils/storage');
var pay = require('../../common/wxpay');

var pageSetting = {
	data:{
		modalHidden: true,
		orderData : {},
        shippingDesc: '', // 运费
        actSpec : '', // 规格
		remainTimeStr : '',
		isShowMask : false,
		logisticsData : {},
		reasonIdx : null,
		reasonArr : [
			'不想要了/下错单',
			'操作有误（地址、商品写错）',
			'货品质量问题／过了生产日期',
			'快递一直未到，不能按时送达',
			'未按照约定时间发货', 
			'货送错了／量送少了',
			'其他原因'
		],
        articleId: ''
	},
    onLoad: function(options){
        modal.loading();
        app.globalData.orderDetailComment = false;
        var that = this;
        var order_id = options.order_id;
        var orderData = that.data['orderData'];
        var remainTimeStr = that.data['remainTimeStr'];
        var isShowMask = that.data['isShowMask'];
        var logisticsData = that.data['logisticsData'];
        var actSpec =  that.data['actSpec'];
        var shippingDesc = that.data['shippingDesc'];
        var articleId = that.data['articleId'];

        //将order_id存储到setStorage里
        wx.setStorage({
          key: 'order_id',
          data: order_id
        })
        request.post({
            path: '/wxapp_api/api'
        },{"dp:api:act:orderInfo":{"order_id":order_id}})
	        .then(function(res){
	        	orderData = res['dp:api:act:orderInfo'];
                if(orderData.ret != 0){
                    // modal.toast(orderData.msg);
                    wx.navigateTo({
                        url: "../error/error"
                    })
                    return false;
                }
                actSpec = (orderData.data.act_spec).split(',')[1];
                shippingDesc = orderData.data.shipping_desc;
                if(shippingDesc != '免运费') {
                    shippingDesc = parseFloat(shippingDesc);
                }
	        	
	        	//剩余时间
	        	if(orderData.data.status == '3'){
	        		var remainTime = {};
	        		var timeStr = (orderData.data.create_time).replace(/-/g,"/");
	        		var nowTime = Date.parse(new Date()) / 1000;
					var oldTime = Date.parse(new Date(timeStr)) / 1000;
	        		var t = 3600*24*15 - (nowTime - oldTime);
	        		remainTime.days = (parseInt(t/3600/24)).toString();
	        		remainTime.hours = (parseInt((t%(3600*24))/3600)).toString();
	        		remainTimeStr = '还剩'+remainTime.days+'天'+remainTime.hours+'时自动确认收货';
	        	}
	        	//物流信息
	        	if(orderData.data.logistics){
	        		var logistics = orderData.data.logistics.split(':');
	        		logisticsData.company = logistics[0];
                    logisticsData.order = [];
                    var logisticsOrder = logistics[1].split(',');
                    if(logisticsOrder.length == 1) {
                        logisticsData.order[0] = logisticsOrder;
                    }else{
                        for(var i=0;i<logisticsOrder.length;i=i+2){
                            if(logisticsOrder.length/2 != 0 && i == logisticsOrder.length-1){
                                logisticsData.order[i/2] = logisticsOrder[i];
                            }else{
                                logisticsData.order[i/2] = logisticsOrder[i]+','+logisticsOrder[i+1];    
                            }
                        }
                    }	
        		}
	        	
	        	that.setData({
		        	orderData : orderData,
		        	remainTimeStr : remainTimeStr,
		        	logisticsData : logisticsData,
                    actSpec : actSpec,
                    shippingDesc : shippingDesc
		        });
		        modal.hide();
	        });
    },
    onShow: function(){
        if(app.globalData.orderDetailComment) {
            modal.loading();
            app.globalData.orderDetailComment = false;
            var that = this;
            var order_id = wx.getStorageSync('order_id');
            var orderData = that.data['orderData'];
            var remainTimeStr = that.data['remainTimeStr'];
            var isShowMask = that.data['isShowMask'];
            var logisticsData = that.data['logisticsData'];
            var actSpec =  that.data['actSpec'];
            var shippingDesc = that.data['shippingDesc'];
            var articleId = that.data['articleId'];
            request.post({
                path: '/wxapp_api/api'
            },{"dp:api:act:orderInfo":{"order_id":order_id}})
                .then(function(res){
                    orderData = res['dp:api:act:orderInfo'];
                    if(orderData.ret != 0){
                        // modal.toast(orderData.msg);
                        wx.navigateTo({
                            url: "../error/error"
                        })
                        return false;
                    }
                    actSpec = (orderData.data.act_spec).split(',')[1];
                    shippingDesc = orderData.data.shipping_desc;
                    if(shippingDesc != '免运费') {
                        shippingDesc = parseFloat(shippingDesc);
                    }
                    
                    //剩余时间
                    if(orderData.data.status == '3'){
                        var remainTime = {};
                        var timeStr = (orderData.data.create_time).replace(/-/g,"/");
                        var nowTime = Date.parse(new Date()) / 1000;
                        var oldTime = Date.parse(new Date(timeStr)) / 1000;
                        var t = 3600*24*15 - (nowTime - oldTime);
                        remainTime.days = (parseInt(t/3600/24)).toString();
                        remainTime.hours = (parseInt((t%(3600*24))/3600)).toString();
                        remainTimeStr = '还剩'+remainTime.days+'天'+remainTime.hours+'时自动确认收货';
                    }
                    //物流信息
                    if(orderData.data.logistics){
                        var logistics = orderData.data.logistics.split(':');
                        logisticsData.company = logistics[0];
                        logisticsData.order = [];
                        var logisticsOrder = logistics[1].split(',');
                        if(logisticsOrder.length == 1) {
                            logisticsData.order[0] = logisticsOrder;
                        }else{
                            for(var i=0;i<logisticsOrder.length;i=i+2){
                                if(logisticsOrder.length/2 != 0 && i == logisticsOrder.length-1){
                                    logisticsData.order[i/2] = logisticsOrder[i];
                                }else{
                                    logisticsData.order[i/2] = logisticsOrder[i]+','+logisticsOrder[i+1];    
                                }
                            }
                        } 
                    }
                    
                    that.setData({
                        orderData : orderData,
                        remainTimeStr : remainTimeStr,
                        logisticsData : logisticsData,
                        actSpec : actSpec,
                        shippingDesc : shippingDesc
                    });
                    modal.hide();
                });    
        }
        
    },
    showPayMask : function(e){
    	//申请退款
    	var that = this;
    	that.setData({
            isShowMask : true
        });
    },
    hidePayMask : function(e){
    	//取消申请退款
    	var that = this;
    	that.setData({
            isShowMask : false
        });
    },
    bindPickerChange: function(e) {
    	//申请退款原因
	    var that = this;
	    var reasonIdx = e.detail.value;
	    that.setData({
	    	index: e.detail.value,
	    	reasonIdx : reasonIdx
    	})
	},
    refundChange : function(e){
    	//申请退款确定
    	var that = this;
    	var data = e.currentTarget.dataset;
    	var reason = data.reason;
        var orderId = data.order_id;
        var oldStatus = data.status;
        var reasonIdx = that.data.reasonIdx;
        var data = {
            'dp:api:act:refund':{
                'id':orderId,
                'reason':reason
            }
        }
        if(!reason && !reasonIdx){
        	modal.toast('请选择退款原因','提示',function(){
		    });
		    return false;
        }else{
			request.post({
	            path: '/wxapp_api/api'
	        },data)
	            .then(function(res){
	                var retData = res['dp:api:act:refund'];
	                var orderData = that.data.orderData;
	                var remainTimeStr = that.data.remainTimeStr;
	                var logisticsData = that.data.logisticsData;
	                var isShowMask = false;
	                if(retData.ret != 0){
	                  // modal.toast(retData.msg);
                      wx.navigateTo({
                        url: "../error/error"
                      })
	                  return false;
	                }
	                
		        	if(orderData.data.logistics){
		        		var logistics = orderData.data.logistics.split(':');
		        		logisticsData.company = logistics[0];
		        		logisticsData.order = logistics[1];	
	        		}
	                if (retData['data']['status']){
	                    orderData['data']['status_desc'] = '申请退款中';
	                    orderData['data']['status'] = '12';
	                    app.globalData.listOrderState = true;
	                    modal.toast('提交成功','提示',function(){
	                    });
	                }
	                that.setData({
			        	isShowMask : isShowMask,
	                    orderData : orderData,
			        	remainTimeStr : remainTimeStr,
			        	logisticsData : logisticsData,
			        	reasonIdx : reasonIdx
	                })
	            });
        }
        
    },
    clickGoPay:function(e){
    	//立即支付按钮
	    var data = e.currentTarget.dataset;
        app.globalData.listOrderState = true;
	    // wx.navigateTo({
	    //     url: '../submit/submit?order_id='+data.order_id
	    // })
        pay.callwxPay(data.order_id)
    },
    modalTap: function(e) {
        //申请售后按钮 有电话号码拨打电话没有电话号码显示提示
        var data = e.currentTarget.dataset;
        var phone = data.service_phone.split('/')[0]; //有多个手机号，默认拨打第一个
        if(data.service_phone != ''){
            wx.makePhoneCall({
                phoneNumber: phone 
            })
        }else{
            this.setData({
                modalHidden: false
            }) 
        }
    },
    modalChange: function(e) {
        //申请售后确定按钮
        this.setData({
            modalHidden: true
        })
    },
    clickGoConfirm:function(e){ 
    	//确认收货 
        var that = this;    
        var odata = e.currentTarget.dataset;
        var orderData = that.data.orderData;
        var data = {
            'dp:api:act:confirmGoods':{
                id:odata.order_id
            }
        }
        request.post({
            path: '/wxapp_api/api'
        },data)
        .then(function(res){
            var retData = res['dp:api:act:confirmGoods'];
            if(retData.ret != 0){
              // modal.toast(retData.msg);
              wx.navigateTo({
                    url: "../error/error"
                })
              return false;
            }else{
                orderData['data']['status_desc']='已收货';
                orderData['data']['status']='4';
                app.globalData.listOrderState = true;
                modal.toast('操作成功','提示',function(){
                });
            }
            that.setData({
                orderData:orderData
            })  
        });
    }
}

utils.assign(pageSetting);
Page(pageSetting);